package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.bean.ApiResponse;
import com.example.demo.entity.User;
import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;

@RestController
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public String login(@RequestBody String userId) {
        // 生成 token
        String token = tokenService.generateToken(userId);
        // 保存 token 到 Redis
        tokenService.saveToken(token, userId);
        return token;
    }

    @GetMapping("/validate")
    public String validateToken(@RequestParam String token) {
        String userId = tokenService.getUserIdFromToken(token);
        if (userId != null) {
            return "Token is valid for user: " + userId;
        } else {
            return "Invalid token";
        }
    }

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> registerUser(@RequestBody User user) {
        try {
            User registeredUser = userService.registerUser(user);
            ApiResponse<User> response = new ApiResponse<User>(true, "User registered successfully", registeredUser);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            ApiResponse<User> response = new ApiResponse<User>(false, e.getMessage(), null);
            return ResponseEntity.badRequest().body(response);
        }
    }
}
